const https = require('https')
const http = require('http')
const querystring = require('querystring')
const crypto = require('crypto')


//静态API

let pubApi = {
    "SecretId":'AKIDyshOvNVze86zhEbulSCqKftBKJ7zeLxc',

    "SignatureMethod":"HmacSHA1",

    "Timestamp" : Math.round(Date.now()/1000),

    "Nonce" : Math.round(Math.random()*100000)

}

let genpubapi = ()=>{

    return pubApi ={

        "SecretId":'AKIDyshOvNVze86zhEbulSCqKftBKJ7zeLxc',

        "SignatureMethod":"HmacSHA1",

        "Timestamp" : Math.round(Date.now()/1000),

        "Nonce" : Math.round(Math.random()*100000)

    }

}


//动态构造OB

    const staicOB = (ob,...key) =>{

    for (let index = 0; index < key.length; index++) {

    ob[key[index][0]] = key[index][1]

    }

return ob

}

//排序ob

let obup = (object)=>{

    let obt = {};

    let keys = Object.keys(object).sort()

    keys.forEach(e =>{

        obt[e] = object[e]

    })

    return obt

}

//生成加密字符串

const sha1starting = (type,url,ob)=>{

    let SecretKey='wwz3APmBe9hGtaKQZlyGfAnSBxmdWSRS'

    let str = ''

    str = type+url+querystring.stringify(ob)
    if(ob.recordLine)
    {
        ob.recordLine = '默认'
        str = str.replace('%E9%BB%98%E8%AE%A4','默认')
    }
    
    //console.log("打印加密前的参数URL\n",str)
    const cry= crypto.createHmac('sha1',SecretKey)
    let crystr = cry.update(new Buffer(str, 'utf8')).digest('base64')
    

    return crystr

}

//生成访问URL

const geturl = (str)=>{

    let url = 'https://cns.api.qcloud.com/v2/index.php?&'

    url+=str

    return url

}

//获取https请求后的json数据
const HttpsGetJsonAsync = (url,type)=>{

    let p = new Promise((res,rej)=>{

        let str = ''
        switch (type) {
            case 'https':
                https.get(url,(r) =>{
                r.setEncoding('utf8');
                r.on('data',(d)=>{
    
                    str += d
    
                    })
    
                r.on('end',()=>{
        
                        res(str)
        
                        })
        
                })
                break;
            case 'http':
            http.get(url,(r) =>{
                r.setEncoding('utf8');
                r.on('data',(d)=>{
    
                    str += d
    
                    })
    
                r.on('end',()=>{
        
                        res(str)
        
                        })
        
                })
                break;
            default:
                break;
        }
        

    })

return p

}

//请求查询域名列表接口（RecordList）

let RecordListJsonAsync = (ob)=>{

    let p = new Promise((res,rej)=>{

    ob = staicOB(ob,['Action','RecordList'],['domain','vleboy.cn'],["subDomain","wxapp"])

    ob = obup(ob)

    ob.Signature = sha1starting('GET','cns.api.qcloud.com/v2/index.php?',ob)

    let url= geturl(querystring.stringify(ob))

    res(url)

    })

    return p

}

//获取子域名的ID IP DOMIN信息

let info = async (subdomin)=>{

    let url = await RecordListJsonAsync(pubApi)

   // console.log("打印请求URL",url)

    let json = await HttpsGetJsonAsync(url,'https')

  //  console.log("打印现有子域名信息\n",json)

    let j = JSON.parse(json)

    let id,ip,domin,line ='';

    j.data.records.forEach(e =>{

    if(e.name === subdomin)

    {

    id = e.id

    ip = e.value

    domin = e.name

    line = e.line

    }

    }

    )

    return {

    "id":id,

    "ip":ip,

    "domin":domin,

    "line":line

    }

}

//设置新的域名解析

let setNewsubdomin = async (domin,type)=>{

    console.log('开始检查更新')
    console.log('检查当前IP地址')
    //查询当前IP
    let ip = await getip().catch((e)=>{
        console.log('IP地址检查失败,错误为',e)
        return
    })

    ip = ip.query
    console.log('查询成功，当前IP地址为',ip)
    //查询现有子域名ID IP
    console.log('开始查询子域名信息')
    
    let obj = await info(domin).catch((e)=>{
        console.log('子域名检查失败,错误为',e)
        return 
    })
    console.log("子域名查询成功，打印子域名查询信息",obj)
    console.log('检查IP是否需要更新')
    if(ip === obj.ip) 
    {
        console.log('子域名IP与现有IP一致,为：',ip,'不需要更新')
        return
    }
    console.log('子域名IP与现有IP不一致，开始更新')
    let o =genpubapi()

    //构造设置域名的结构

    obj =staicOB(o,["Action","RecordModify"],["domain","vleboy.cn"],["recordId",+obj.id],["subDomain",domin],["recordType",type],["recordLine",obj.line],["value",ip])

    obj = obup(o)

    obj.Signature = sha1starting('GET','cns.api.qcloud.com/v2/index.php?',obj)
    let ur = querystring.stringify(obj)

    let url= geturl(ur)

    
    let json = await HttpsGetJsonAsync(url,'https').catch((e)=>{
        console.log('更新失败,错误为',e)
        return
    })

    console.log("更新成功",json)

}

//获取当前IP
let getip = async()=>{

    const getipurl = 'http://ip-api.com/json'
    let json = await HttpsGetJsonAsync(getipurl,'http')
    let j = JSON.parse(json)
    return j
   
}



let ss = async ()=>{
    await setNewsubdomin('wxapp','A')
}
ss()
setInterval(ss,1000*60)
